/*
 * Copyright (C) 2006 Johan Maasing johan at zoom.nu Licensed under the Apache
 * License, Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
 * or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package nu.zoom.swing.desktop.component.stringmenu.impl;

import java.io.Serializable;
import java.util.HashMap;

import nu.zoom.swing.desktop.Workbench;
import nu.zoom.swing.desktop.component.stringmenu.StringMenu;
import nu.zoom.swing.desktop.component.stringmenu.StringMenuFactory;
import nu.zoom.swing.desktop.preferences.Preferences;
import nu.zoom.swing.desktop.worker.WorkerFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class StringMenuFactoryImpl implements StringMenuFactory {
	private final HashMap<String, StringMenu<?>> menuCache = new HashMap<String, StringMenu<?>>();

	private final Preferences preferences;

	private final Workbench workbench;

	private final Log log = LogFactory.getLog(getClass());

	public StringMenuFactoryImpl(Preferences preferences, Workbench workbench) {
		this.preferences = preferences;
		this.workbench = workbench;
	}

	@Override
	@SuppressWarnings("unchecked")
	public <T extends Comparable<T> & Serializable> StringMenu<T> getMenu(
			final Class<T> clazz, final String preferenceKey) {
		if (!menuCache.containsKey(preferenceKey)) {
			log.trace("Creating new string menu");
			StringMenu<T> menu = new StringMenuImpl<T>(preferences, workbench,
					preferenceKey);
			menu = WorkerFactory.decorate(menu, StringMenu.class);
			menuCache.put(preferenceKey, menu);
		}
		return (StringMenu<T>) menuCache.get(preferenceKey);
	}

}
